package org.itboys.mobile.service.mongo.web;


import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.dto.lasted.SundayUploadDto;
import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.entity.lasted.SystemRole;
import org.itboys.admin.entity.lasted.SystemUser;
import org.itboys.admin.entity.lasted.SystemUserRole;
import org.itboys.admin.service.lasted.*;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.SundayMemberDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.util.NameUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.security.provider.Sun;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_用户_service
 */
@Service
public class SundayMemberService extends BaseMongoService<SundayMember> {

    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundayUploadService uploadService;

    @Autowired
    private SystemUserService userService;
    @Autowired
    private SystemRoleService roleService;
    @Autowired
    private SystemUserRoleService userRoleService;











    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }

    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }
    /**
     * 分页获取用户信息
     * @param request
     * @return
     */
    public PageResult<SundayMember> selectMember(HttpServletRequest request,List<Integer> userTypes ){
        Map<String,Object> param =ParamUtil.packageMongoExactParam(request,"userType","status","parentId");
        param.put("isDeleted", 0);
        if(ListUtil.isNotNull(userTypes)){
            param.put("userType in",userTypes);
        }
        Map<String,String> containsparam = ParamUtil.packageMongoVagueParam(request,"nickName","mobileName","mobile");

        return super.containpageQuery(request,containsparam,param);
    }
    /**
     * 分页获取用户信息
     * @param request
     * @return
     */
    public List<SundayMember> selectMemberNoPage(HttpServletRequest request,List<Integer> userTypes){
        Map<String,Object> param =ParamUtil.packageMongoExactParam(request,"userType");
        param.put("isDeleted", 0);
        param.put("parentId",0);
        if(ListUtil.isNotNull(userTypes)){
            param.put("userType in",userTypes);
        }
        return super.list(param);
    }

    /**
     * 修改或新增
     * @param member
     */
    public void saveMember(SundayMember member,
                           MultipartFile imageFile,
                           MultipartFile[] rollImageFiles) throws  Exception {
        //保存主图
        Map<String, String> map = uploadService.uploadSingle(imageFile);
        if(StringUtils.isNotEmpty(map.get(uploadService.UPLOAD_HALF_PATH))){
            member.setImage(map.get(uploadService.UPLOAD_HALF_PATH));
        }
        //默认正常

        Map<String,Object> param =new HashMap<String, Object>();
        if(member.getId()==0l){
            param.put("isDeleted",0);
            param.put("mobile",member.getMobile());
            if(ListUtil.isNotNull(super.list(param))){
                throw new ErrorException("手机号不能重复");
            }
            //生成默认头像
         //   member.setImage(NameUtil.getRandomLogo());
            if(StringUtils.isNotEmpty(member.getPassword())){
                member.setPassword(Digests.md5(member.getPassword()));
            }
            //2017年8月27日
            member.setStatus(SundayCommonConstants.NO);
            super.save(member);
            if(member.getUserType()== SundayCommonConstants.user_type_business){
                //绑定登陆账号角色
                param.clear();
                param.put("isDeleted",0);
                param.put("name","商户角色");
                List<SystemRole> roles = roleService.list(param);
                if(ListUtil.isNull(roles))return;
                //，2017年9月25日，给商户添加后台登陆账号
                SystemUser user = new SystemUser();
                user.setMobile(member.getMobile());
                user.setUserName(member.getMobile());
                //手机号后6位
                String password=member.getMobile().substring(member.getMobile().length()-6,member.getMobile().length());
                user.setPassword(Digests.md5(password));
                user.setName(member.getNickName());
                user.setIsSuper(SundayCommonConstants.NO);
                user.setStatus(SundayCommonConstants.NO);
                //绑定商户ID
                user.setPlatformMemberId(member.getId());
                userService.save(user);
                //绑定角色
                userRoleService.save(new SystemUserRole(user.getId(),roles.get(0).getId()));
            }



        }else{
            param.put("id !=",member.getId());
            param.put("isDeleted",0);
            param.put("mobile",member.getMobile());
            if(ListUtil.isNotNull(super.list(param))){
                throw new ErrorException("手机号不能重复");
            }
            if(StringUtils.isNotEmpty(member.getPassword())){
                member.setPassword(Digests.md5(member.getPassword()));
            }
            super.updateExceptEmpty(member.getId(),member);
        }
        uploadService.uploadMultiWithRecord(rollImageFiles,member.getId(),SundayProduct.class.getSimpleName(),"商户ID="+member.getId()+",的轮播图");






    }

    /**
     *  单个用户查询
     * @param id
     * @param userType
     * @return
     */
    public SundayMember findOne(Long id,Integer userType) {
        SundayMember member =null;
        if(LongUtil.isNotZreo(id)){
            member=super.getById(id);
            //加载轮播图
            Map<String,Object> imgParam = new HashMap<String, Object>();
            imgParam.put("outClassName", member.getClass().getSimpleName().toString());
            imgParam.put("outClassId", id);
            List<SundayUploadDto> rollImages = uploadService.selectNoPage(member.getId(),SundayProduct.class.getSimpleName());
           // member.setRollImages(rollImages);
            //加载商户分类
        }else{
            member=new SundayMember();
            member.setId(0);
            member.setUserType(userType);

        }
        member.setPassword(null);
        return member;
  }
    /**
     * 重置为默认密码
     * @param id
     */
    public void resetPassword(Long id){
            super.update(id,"password",Digests.md5(SundayCommonConstants.default_password));

    }
    /**
     * 冻结或启用用户账号
     * @param id
     */
    public void changeStatus(Long id,Integer status){
        super.update(id,"status",status);
    }


}
